﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Smarts.Controls
{
    /// <summary>
    /// A proxy class used in conjunction with a
    /// <see cref="CollectionManager"/> to provide strongly
    /// typed access to the <see cref="CollectionManager"/>
    /// control
    /// </summary>
    /// <typeparam name="T">The type of objects listed in the <see cref="CollectionManager"/></typeparam>
    public class CollectionManagerProxy<T>
    {
        private List<T> _items;

        private CollectionManager _collectionManager;

        private CollectionManagerProxy()
        {

        }

        /// <summary>
        /// The items in the list, strongly typed.
        /// This property needs to be assigned to in order to update the list
        /// </summary>
        public List<T> Items
        {
            get {
                ExtractItems();
                return _items;
            }
            set {
                _items = value;
                PublishItems();
            }
        }

        /// <summary>
        /// Adds an item to the list with an immediate publish to
        /// the control
        /// </summary>
        /// <param name="Item">The item to add</param>
        public void Add(T Item)
        {
            _items.Add(Item);
            PublishItems();
        }

        /// <summary>
        /// Pushes the items to the collection manager
        /// </summary>
        private void PublishItems()
        {
            if (_collectionManager == null)
            {
                throw new InvalidOperationException("A collection manager has not been assigned");
            }
            _collectionManager.Items = (from item in _items
                                        select (object)item).ToList();
        }

        private void ExtractItems()
        {
            if (_collectionManager == null)
            {
                throw new InvalidOperationException("A collection manager has not been assigned");
            }
            _items = (from item in _collectionManager.Items
                      select (T)item).ToList();
        }

        /// <summary>
        /// The constructor for the proxy
        /// </summary>
        /// <param name="DestinationCollectionManager">The <see cref="CollectionManager"/> to bind to</param>
        public CollectionManagerProxy(CollectionManager DestinationCollectionManager)
        {
            _collectionManager = DestinationCollectionManager;
        }
    }
}
